package cn.iocoder.yudao.module.jikong.service.address;

import cn.hutool.core.collection.CollUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.jikong.controller.admin.address.vo.*;
import cn.iocoder.yudao.module.jikong.dal.dataobject.address.AddressDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.jikong.dal.mysql.address.AddressMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.yudao.module.jikong.enums.ErrorCodeConstants.*;

/**
 * 地址管理 Service 实现类
 *
 * @author admin
 */
@Service
@Validated
public class AddressServiceImpl implements AddressService {

    @Resource
    private AddressMapper addressMapper;

    @Override
    public Long createAddress(AddressSaveReqVO createReqVO) {
        // 插入
        AddressDO address = BeanUtils.toBean(createReqVO, AddressDO.class);
        addressMapper.insert(address);
        // 返回
        return address.getId();
    }

    @Override
    public void updateAddress(AddressSaveReqVO updateReqVO) {
        // 校验存在
        validateAddressExists(updateReqVO.getId());
        // 更新
        AddressDO updateObj = BeanUtils.toBean(updateReqVO, AddressDO.class);
        addressMapper.updateById(updateObj);
    }

    @Override
    public void deleteAddress(Long id) {
        // 校验存在
        validateAddressExists(id);
        // 删除
        addressMapper.deleteById(id);
    }

    @Override
        public void deleteAddressListByIds(List<Long> ids) {
        // 校验存在
        validateAddressExists(ids);
        // 删除
        addressMapper.deleteByIds(ids);
        }

    private void validateAddressExists(List<Long> ids) {
        List<AddressDO> list = addressMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(ADDRESS_NOT_EXISTS);
        }
    }

    private void validateAddressExists(Long id) {
        if (addressMapper.selectById(id) == null) {
            throw exception(ADDRESS_NOT_EXISTS);
        }
    }

    @Override
    public AddressDO getAddress(Long id) {
        return addressMapper.selectById(id);
    }

    @Override
    public PageResult<AddressDO> getAddressPage(AddressPageReqVO pageReqVO) {
        return addressMapper.selectPage(pageReqVO);
    }

}